package com.tencent.qcloud.timchat.adapters

import com.chad.library.adapter.base.BaseQuickAdapter
import com.tencent.qcloud.timchat.ImInit
import com.tencent.qcloud.timchat.R
import com.tencent.qcloud.timchat.model.ImChatUser
import com.tencent.qcloud.timchat.model.ImRequestListener
import com.tencent.qcloud.timchat.model.Message

/**
 * 聊天界面adapter
 */
class ChatAdapter : BaseQuickAdapter<Message, ChatViewHolder>(R.layout.item_message) {
    override fun convert(helper: ChatViewHolder, item: Message) {
        item.showRecyclerMessage(helper, mContext)
    }

    override fun addData(item: Message) {
        if (item.chatUser == null) {
            ImInit.requestImChatUser(arrayListOf(item.sender), object : ImRequestListener() {
                override fun success(users: ArrayList<ImChatUser>?) {
                    if (users != null && !users.isEmpty()) {
                        item.chatUser = users[0]
                        notifyDataSetChanged()
                    }
                }

                override fun error(result: Any?) {
                }
            })
        }
        super.addData(item)
    }

    override fun addData(newData: MutableCollection<out Message>) {
        netData(newData)
        super.addData(newData)
    }

    override fun addData(position: Int, newData: MutableCollection<out Message>) {
        netData(newData)
        super.addData(position, newData)
    }

    private fun netData(newData: MutableCollection<out Message>) {
        val needRequestList = ArrayList<String>()
        for (item in newData) {
            if (item.chatUser == null) {
                needRequestList.add(item.sender)
            }
        }
        if (!needRequestList.isEmpty()) {
            ImInit.requestImChatUser(needRequestList, object : ImRequestListener() {
                override fun success(users: ArrayList<ImChatUser>?) {
                    users?.let {
                        for (index in data.indices)
                            for (user in users) {
                                if (data[index].sender == user.imUserName) {
                                    data[index].chatUser = user
                                }
                            }
                        notifyDataSetChanged()
                    }
                }

                override fun error(result: Any?) {
                }
            })
        }
    }
}